package com.jiawei.service.impl;


import com.jiawei.entity.database.User;
import com.jiawei.entity.pojo.Rt;
import com.jiawei.mapper.UserMapper;
import com.jiawei.service.AccessService;
import com.jiawei.util.JwtUtil;
import com.jiawei.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author : willian fu
 * @date : 2019/12/11
 */
@Slf4j
@Service
public class AccessServiceImpl implements AccessService {

    @Value("${customize.token}")
    private String header;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登录接口
     *
     * @param user     账号
     * @param password 密码
     * @return 登录结果
     */
    @Override
    public Object login(String user, String password) {
        User us = userMapper.selectOne(User.builder().username(user).build());
        if (us != null && Md5Util.Md5Decode(password).equals(us.getPassword())){
            HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
            //将token设置到响应头 key = Authenticate
            response.setHeader(header, jwtUtil.jwtGetToken(us));
            //设置允许客户端读取响应头字段
            response.setHeader("Access-Control-Expose-Headers", header);
            us.setPassword(null);
            return Rt.ok(us);
        }else {
            return Rt.notFound("登陆失败，请检查账号或密码");
        }
    }

    /**
     * 注册接口
     *
     * @param user     账号
     * @param password 密码
     * @param code     验证码
     * @return 注册结果
     */
    @Override
    public Object registry(String user, String password, String code) {
        String cd = redisTemplate.opsForValue().get("code:" + user);
        if (code.equals(cd)){
            List<User> select = userMapper.select(User.builder().username(user).build());
            if (select.size() > 0){
                return Rt.badRequest("注册失败，用户已存在");
            }else {
                userMapper.insertSelective(User.builder().username(user).password(Md5Util.Md5Decode(password)).build());
                return Rt.noContent("注册成功");
            }
        }
        return Rt.badRequest("注册失败，验证码错误");
    }

    @Override
    public Object getCode(String user) {
        if (null != userMapper.selectOne(User.builder().username(user).build())){
            return Rt.badRequest("用户已存在，请更换账户名");
        }
        Random random = new Random();
        int rand = random.nextInt(9999) + 2000;
        redisTemplate.opsForValue().set("code:" +user, String.valueOf(rand), 5, TimeUnit.MINUTES);
        return Rt.ok(rand);
    }
}
